import React,{useState} from 'react'
import style from './index.module.less'
import {Form,Input,Button,Card,Spin,message} from 'antd'
import { sendActionPOST } from '../../utils/axios'
import { loginURL } from '../../utils/api'

const Login =(props)=>{

    const [isLoading,setIsLoading] = useState(false)

    const onFinish=async(e)=>{
        setIsLoading(true)
        const res = await sendActionPOST(loginURL,{
            username:e.username,
            password:e.password
        })
        if(res.data.data==='登录成功'){
            setIsLoading(false)
            localStorage.setItem('openId',res.data.openId)
            props.history.push('/index')
        }else{
            setIsLoading(false)
            message.error('登录失败')
        }
    }

    const onFinishFailed=()=>{
        message.error('用户名或密码不能为空')
    }

    return(
        <div className={style.container}>
        <Spin spinning={isLoading}>
            <Card title='小小姜的博客' bordered={true} style={{width:400}}>
            <Form name='login' initialValues={{remember:true}}
            onFinish={onFinish} onFinishFailed={onFinishFailed} >
                <Form.Item label='username' name='username'
                rules={[{required:true,message:'用户名不能为空'}]}>
                    <Input placeholder='请输入用户名'/>
                </Form.Item>
                <Form.Item label='password' name='password' 
                rules={[{required:true,message:'密码不能为空'}]}>
                    <Input.Password placeholder='请输入密码'/>
                </Form.Item>
                <Form.Item wrapperCol={{offset:8,span:16}}>
                    <Button type='primary' htmlType='submit'>
                        Login in
                    </Button>
                </Form.Item>
            </Form>
            </Card>
        </Spin>
        </div>
    )
}

export default Login